package com.huibeili.interceptor;


import com.huibeili.system.domain.SysOperLog;
import com.huibeili.system.mapper.SysOperLogMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;

/**
 * JWT登录授权过滤器
 * https://github.com/shenzhuan/mallplus on 2018/4/26.
 */
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    private static final Logger LOGGER = LoggerFactory.getLogger(JwtAuthenticationTokenFilter.class);
    @Resource
    public SysOperLogMapper fopSystemOperationLogService;

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain chain) throws ServletException, IOException {
        long startTime, endTime;

        String requestType = ((HttpServletRequest) request).getMethod();
        SysOperLog sysLog = new SysOperLog();
        String fullUrl = ((HttpServletRequest) request).getRequestURL().toString();

        int startIntercept = fullUrl.replace("//", "a").indexOf("/") + 2;
        String interfaceName = fullUrl.substring(startIntercept, fullUrl.length());



        startTime = System.currentTimeMillis();
        try {
            chain.doFilter(request, response);
        } catch (Exception e) {
            e.printStackTrace();
        }

        endTime = System.currentTimeMillis();

        sysLog.setCreateTime(new Date());

        sysLog.setMethod(interfaceName);


        sysLog.setOperatorType((int) (endTime - startTime));
        if (!"OPTIONS".equals(requestType) && !interfaceName.contains("webjars")
                && !interfaceName.contains("api-docs")) {
            sysLog.setBusinessType(999);
        fopSystemOperationLogService.insertOperlog(sysLog);
        }
    }


}
